import axios from 'axios';
// 定义常量记录地址信息
import { api } from '../../../http/default';
import { URL } from '../../../http/env.config';
import { videoAddVideoPicApi } from '../../../http/request';
// 随机字符串
const randomDir = () => {
    let dt = new Date();
    let YY:any = dt.getFullYear();
    let MM:any = dt.getMonth() + 1;
    let DD:any = dt.getDate();
    let  h:any  = dt.getHours();
    let  m:any  = dt.getMinutes();
    let  s:any  = dt.getSeconds();
    MM = MM < 10 ? '0' + MM : MM;
    DD = DD < 10 ? '0' + DD : DD;
    h = h < 10 ? '0' + h : h;
    m = m < 10 ? '0' + m : m;
    s = s < 10 ? '0' + s : s;
    let str = Math.random().toString().slice(2, 8);
    return `${YY}${MM}${DD}_${str}`;
}

// 加入并发控制
export const  SliceUpload:any = (elementInput:any,video_title:string, video_author:string, video_text:string, video_navigate:string,video_pic:any) => {
    // console.log('video_pic:',video_pic)
    return new Promise((resolve:any,reject:any)=>{
        const file = elementInput.files[0]
        const vRandomDir = randomDir();
        let token = localStorage.getItem('token')
        if (!file) return
        // 文件分片
        let size = 1024 * 50; // 分片大小设置
        let fileChunks = [];
        let index = 0;        // 分片序号
        for (let cur = 0; cur < file.size; cur += size) {
            fileChunks.push({
                hash: index++,
                chunk: file.slice(cur, cur + size),
            });
        }
        const uploadFileChunks = async function (list:any) {
            if (list.length === 0) {
                // 所有分片上传完成，通知如无
                await axios({
                    method: 'get',
                    // url: 'http://localhost:3002/video/merge',
                    url: URL+api.video.merge,
                    headers: {
                        token: token,
                    },
                    params: {
                        filename: file.name,
                        randomDir: vRandomDir,
                        token: token,
                        video_title: video_title,
                        video_author: video_author,
                        video_text: video_text,
                        video_navigate: video_navigate,
                        video_pic: video_pic,
                    }
                }).then(
                    res => {
                        console.log('-->', res);
                    }
                )
                    .catch(
                        err => {
                            console.log(err);
                        }
                    )
                return false;
            }
    
            let pool:any = []       // 并发池
            let max = 3         // 最大并发数
            let finish = 0      // 完成数量
            let failList:any = []   // 失败列表
            for (let i = 0; i < list.length; i++) {
                let item = list[i]
                let formData = new FormData()
                formData.append('filename', file.name)
                formData.append('hash', item.hash)
                formData.append('chunk', item.chunk)
                formData.append('randomDir', vRandomDir)
                let task = axios({
                    method: 'post',
                    // url: 'http://localhost:3002/video/upload',
                    url: URL+api.video.upload,
                    data: formData
                })
                task.then((data) => {
                    // 从并发池中移除已经完成的请求
                    let index = pool.findIndex((t:any) => t === task)
                    pool.splice(index)
                }).catch(() => {
                    failList.push(item)
                }).finally(() => {
                    finish++
                    // 如果有失败的重新上传
                    if (finish === list.length) {
                        uploadFileChunks(failList)
                    }
                })
                pool.push(task)
                if (pool.length === max) {
                    await Promise.race(pool);
                }
            }
        }
        uploadFileChunks(fileChunks);
        resolve()
    })
}
